package com.linghu.service;

import com.linghu.dao.BillDAO;
import com.linghu.dao.DiningTableDAO;
import com.linghu.dao.MultiTableDAO;
import com.linghu.domain.Bill;
import com.linghu.domain.MultiTableBean;

import java.util.List;
import java.util.UUID;

/**
 * @author 令狐荣豪
 * @version 1.0
 * 处理和账单相关的业务
 */
public class BillService {
    //定义billDAO属性
    private BillDAO billDAO = new BillDAO();
    //定义menuService属性
    private MenuService menuService = new MenuService();
    //定义DiningTableService属性
    private DiningTableService diningTableService = new DiningTableService();

    private MultiTableDAO multiTableDAO=new MultiTableDAO();


    //编写一个点餐的方法
    //1、生成账单
    //2、更新对应餐桌的状态
    public boolean orderMenu(int menuID, int nums, int diningTableId) {
        //生成一个账单号UUID
        String billID = UUID.randomUUID().toString();

        //将账单生成到bill表
        int update = billDAO.update("insert into bill values(null,?,?,?,?,?,now(),'未结账')",
                billID, menuID, nums, menuService.getMenuById(menuID).getPrice() * nums, diningTableId);
        if (update <= 0) {
            return false;
        }
        //需要更新对应餐桌的状态
        return diningTableService.updateDiningTableState(diningTableId, "就餐中");
    }

    //返回所有的账单
    public List<Bill> list() {
        return billDAO.queryMultiple("select * from bill", Bill.class);
    }

    //返回所有的账单并带有菜品名
    public List<MultiTableBean> list2() {
        return multiTableDAO.queryMultiple("select bill.*,name from bill,menu where bill.menuId=menu.id", MultiTableBean.class);
    }


    //查看某个餐桌是否有未结账的账单
    public boolean hasPayBillByDiningTableId(int diningTableId) {

        Bill bill =
                billDAO.querySingle("select * from bill where diningTableId=? and state='未结账' limit 0,1", Bill.class, diningTableId);
        return bill != null;
    }

    //完成结账(如果餐桌存在，并且该餐桌有未结账的账单)
    public boolean payBill(int diningTableId, String payMode) {
        //1、修改bill表
        int update =
                billDAO.update("update bill set state=? where diningTableId=? and state='未结账'", payMode, diningTableId);
        if (update < 0) {//更新不成功
            return false;
        }

        //2、修改diningTable表
        if (!(diningTableService.updateDiningTableToFree(diningTableId, "空"))) {
            return false;
        }
        return true;
    }
}
